<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use think\Db;
use think\Image;

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

//获取两点之间的距离 返回为米
function distanceHaversine($lat1, $lon1, $lat2, $lon2)
{
    $earthRadius = 6371; // 地球半径，单位为千米
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = $earthRadius * $c;
    return $distance;
}


function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(1000000, 9999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }

}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标(高德)
 */
function getTencentLngLat($address)
{
    $key = config('wechat.geocodeMap_1');
    $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . $key . '&address=' . urlencode($address);
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == '1') {
        $jsonResponse['geocodes'][0]['location'] = explode(',', $jsonResponse['geocodes'][0]['location']);
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['geocodes'][0]['location']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 *腾讯地图
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_ten');
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?address=' . urlencode($address) . '&key=' . $key;
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == 0) {
        $address = $jsonResponse['result']['location'];
        $data[] = $address['lng'];
        $data[] = $address['lat'];
        return json_encode(array(
            'code' => 0,
            'data' => $data
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 *腾讯地图 通过坐标地址 获取关键字地址
 */
function getAddressListByKeywords($city, $latitude, $longitude, $keyword, $page)
{
    //https://apis.map.qq.com/ws/place/v1/search
    //https://apis.map.qq.com/ws/place/v1/search
    //https://apis.map.qq.com/ws/place/v1/explore
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude . ',10,1';
    $nearby2 = $city . ',0,' . $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/place/v1/search?boundary=region(' . $nearby2 . ')&keyword=' . $keyword . '&page_size=20&page_index=' . $page . '&orderby=_distance&key=' . $key;
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['data']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

/**
 *腾讯地图 通过坐标地址 获取位置信息
 */
function getAddressByLocation($latitude, $longitude)
{
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $nearby . '&key=' . $key . '&get_poi=0';
    $response = file_get_contents($url);

    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['result']['ad_info']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

function getAddressByLocation2($latitude, $longitude)
{
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $nearby . '&key=' . $key . '&get_poi=0';
    $response = file_get_contents($url);

    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['result']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

//https://apis.map.qq.com/ws/place/v1/search?boundary=nearby(40.040589,116.273543,1000)&keyword=公园&page_size=10&page_index=1&key=IMYBZ-5AKKQ-ERR5D-BIXJS-ELTY3-3ZFFF
//poi  关联
//https://apis.map.qq.com/ws/poi_association/v1?&location=39.99287,116.31025&title=北京大学&key=OB4BZ-D4W3U-*****


/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

/**
 * 获取前天范围内的时间戳
 */
function getTimestampScope($day = -1, $day2 = -1)
{
    $time1 = getTimestamp($day);
    $time2 = getTimestamp($day2);
    return array(
        0 => $time1[0],
        1 => $time2[1]
    );
}

function objectToArray($object)
{
    $jsonString = json_encode($object);
    $array = json_decode($jsonString, true);

    return $array;
}

//生成小程序二维码
function qrcode($value, $page, $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($value, [
            'page' => $page,
            'width' => $width,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time());
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }
//        msg(-1, '', $response);
        return $response;
    } catch (\Exception $e) {
//        msg(-1, $e->getMessage(), '');
        return $e->getMessage();
    }
}

//通过时间戳范围获取天数
function getDaysFromTimeStamps($startTimestamp, $endTimestamp)
{
    $startDate = new DateTime();
    $startDate->setTimestamp($startTimestamp);

    $endDate = new DateTime();
    $endDate->setTimestamp($endTimestamp);
    $endDate->modify('+1 day'); // 包含结束日期

    $interval = $startDate->diff($endDate);
    return $interval->days;
}

//通过日期范围 获取每天时间戳范围
function getTimestampsInDateRange($startDate, $endDate)
{
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime($endDate);
    $dateRange = array();
    while ($startTimestamp <= $endTimestamp) {
        $dateRange[] = $startTimestamp;
        $startTimestamp = strtotime('+1 day', $startTimestamp);
    }
    return $dateRange;
}

//给两个时间戳 显示所有年月时间戳范围数组
function getAllMonths($startTimestamp, $endTimestamp)
{
    $months = array();
    $currentTimestamp = $startTimestamp;
    while ($currentTimestamp <= $endTimestamp) {
        $months[] = date('Y--m', $currentTimestamp);
        // 获取下个月的第一天的时间戳
        $currentTimestamp = strtotime("+1 month", $currentTimestamp);
    }
    return $months;
}

//通过年月获取时间戳范围
function getMonthTimestampRange($year, $month)
{
    $startTimestamp = strtotime("{$year}-{$month}-01 00:00:00");
    $endTimestamp = strtotime("+1 month", $startTimestamp) - 1;
    return array($startTimestamp, $endTimestamp);
}

//通过年月获这个月每月的时间戳数组 签到使用

function getMonthTimestamps($year, $month)
{
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $timestamps = [];
    for ($day = 1; $day <= $daysInMonth; $day++) {
        $timestamps[] = strtotime("{$year}-{$month}-{$day}");
    }
    return $timestamps;
}


//检测是否是手机号
function validatePhoneNumber($phoneNumber)
{
    $pattern = '/^\+\d{1,3}\s?\(\d{1,4}\)\s?\d{1,4}-?\d{1,9}$/';
    return preg_match($pattern, $phoneNumber);
}



//通过ip返回地址信息
function getCityByIP()
{
    $ip = $_SERVER['REMOTE_ADDR']; // 获取用户的IP地址
    $url = "http://ip-api.com/json/" . $ip . "?lang=zh-CN"; // 构建查询URL

    // 初始化cURL会话
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应作为字符串返回
    curl_setopt($ch, CURLOPT_HEADER, false); // 不需要头部信息

    // 执行cURL请求
    $response = curl_exec($ch);
    curl_close($ch); // 关闭cURL会话

    // 解析JSON响应
    $data = json_decode($response, true);

    // 检查是否成功获取了位置信息
    if ($data['status'] == 'success') {
        return $data; // 返回城市名
    } else {
        return 'Unknown'; // 未知城市
    }
}

//通过城市返回天气情况

function getWeatherByCity($city)
{

    $url = "https://api.lolimi.cn/API/weather/?city=" . $city; // 构建查询URL
    // 初始化cURL会话
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应作为字符串返回
    curl_setopt($ch, CURLOPT_HEADER, false); // 不需要头部信息
    // 执行cURL请求
    $response = curl_exec($ch);
    curl_close($ch); // 关闭cURL会话
    // 解析JSON响应
    $data = json_decode($response, true);
    // 检查是否成功获取了位置信息
//    return $data;
    if ($data['code'] == 1) {
        return $data['data']; // 返回城市名
    } else {
        return 'Unknown'; // 未知城市
    }
}


//判断是不是今天的时间戳
function isToday($timestamp)
{
    $today = date("Y-m-d"); // 今天的日期
    $date = date("Y-m-d", $timestamp); // 给定时间戳的日期
    return $today === $date;
}



//post请求
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}

function GetCenterFromDegrees($data)
{

    if (!is_array($data)) return FALSE;

    $num_coords = count($data);

    $X = 0.0;
    $Y = 0.0;
    $Z = 0.0;

    foreach ($data as $coord) {

        $lat = deg2rad((float)$coord[0]);
        $lon = deg2rad((float)$coord[1]);

        $a = cos($lat) * cos($lon);
        $b = cos($lat) * sin($lon);
        $c = sin($lat);

        $X += $a;
        $Y += $b;
        $Z += $c;
    }

    $X /= $num_coords;
    $Y /= $num_coords;
    $Z /= $num_coords;

    $lon = atan2($Y, $X);
    $hyp = sqrt($X * $X + $Y * $Y);
    $lat = atan2($Z, $hyp);

    return array(rad2deg($lat), rad2deg($lon));
}





function setSYText($imagePath = '', $text = 'Your Watermark Text', $color = '#ffffff', $fontSize = 20, $fontPath = 'font/fangsong.TTF')
{
// 要处理的图片路径
    //$imagePath = 'uploads/20241210/c3b622d7083e673ebb99e5a01dc2f20b.jpg';
// 实例化图像处理对象
    $image = Image::open($imagePath);
// 添加文字水印
    //$text = 'Your Watermark Text'; // 水印文字
    //$fontPath='font/test.ttf';
    // $fontSize = 20; // 字体大小
    //$color = '#ffffff'; // 水印颜色

// 添加水印，参数依次是水印文字，字体文件，字体大小，颜色以及水印位置
    $image->text($text, $fontPath, $fontSize, $color, 1, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 2, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 3, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 4, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 5, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 6, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 7, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 8, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 9, 0, -45);
//    for ($i=1;$i<=9;$i++){
//        $image->text($text, $fontPath, $fontSize, $color, $i,0,-45);
//    }
// 保存处理后的图片
    //$savePath = 'uploads/20241210/7ca923f0d4923d6e747c4c07d16015111.jpg';
    //$savePath=$imagePath;

    $img_arr = explode('.', $imagePath);
    $type = $img_arr[count($img_arr)-1];// 图片后缀
    $path = ROOT_PATH . 'public/upload/car_image/';
    if (!is_dir($path)) {
        @mkdir($path);
    }
    $imagePath2='upload/car_image/' . md5(time()).rand(000000,999999) . '.' . $type;

    $image->save($imagePath2);
    return $imagePath2;
}

// 剔除可能出现的图片域名
function replaceImgDomain($img_url = '')
{
    $img_url = !empty($img_url) ? trim($img_url) : '';
    if (empty($img_url)) {
        return '';
    }
    $pattern = "/^(https?:\/\/)?([^\/]+)/";
    $string = preg_replace($pattern, "", $img_url);
    $string = !empty($string) ? trim($string) : '';
    $string = !empty($string) ? ltrim($string, '//') : '';
    //return !empty($string) ? '/' . trim($string, '/') : '';
    return !empty($string) ? trim($string, '/') : '';
}

//单条数据转树状数据
function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    $tree = array();// 创建Tree
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[$data[$pk]] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}


function generateRandomNumbers(int $length = 6, bool $secure = false): string {
    if ($length <= 0) {
        throw new InvalidArgumentException('长度必须大于0');
    }

    $result = '';
    for ($i = 0; $i < $length; $i++) {
        $result .= $secure ? random_int(0, 9) : mt_rand(0, 9);
    }
    return $result;
}

function generateRandomString($length = 16) {
    return substr(md5(uniqid(mt_rand(), true)), 0, $length);
}

//激活会员卡
function activeCard($mcard_list_id,$member_id){
    $mcard_list_info=Db::name('mcard_list')
        ->where('id','=',$mcard_list_id)
        ->find();
    $mcard_info=Db::name('mcard')->find($mcard_list_info['mcard_id']);
    $update_data=array(
        'id'=>$mcard_list_id,
        'member_id'=>$member_id,
        'status'=>1,
        'status_time'=>time(),
        'end_time'=>time()+($mcard_info['day_num']*86400),
        'discount'=>$mcard_info['discount']
    );
    Db::name('mcard_list')->update($update_data);
    $mcard_server=Db::name('mcard_server')->where('mcard_id','=',$mcard_list_info['mcard_id'])->select();
    $member_mcard_server_data = array();
    foreach ($mcard_server as $k=>$v){
        $time = time();
        $member_mcard_server_data[]=[
            'mcard_list_id'=>$mcard_list_id,
            'server_id' => $v['server_id'],
            'member_id' => $member_id,
            'server_num' => $v['num'],
            'num'=>$v['num'],
            'create_time' => $time,
            'mcard_id'=>$mcard_list_info['mcard_id'],
        ];
    }
    Db::name('member_mcard_server')->insertAll($member_mcard_server_data);
}

//增加减少积分 type '类型 1签到 2兑换 3下订单 4其他
function addFraction($memberId, $fraction_count = 2, $desc = '用户签到', $type = 1, $is_count = 1, $object_cate = '', $goods_order_id = '',$order_no='',$order_type='')
{
    $insert_data = array(
        'member_id' => $memberId,
        'create_time' => time(),
        'count' => $fraction_count,
        'sign_time' => date('Y-m-d', time()),
        'desc' => $desc,
        'type' => $type,
        'is_count' => $is_count,
        'object_cate' => $object_cate,
        'goods_order_id' => $goods_order_id,
        'order_no' => $order_no,
        'order_type' => $order_type,
    );
    Db::name('fraction_record')->insertGetId($insert_data);
    if ($is_count == 1) {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setInc('fraction', $fraction_count);
    } else {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setDec('fraction', $fraction_count);
    }
}

//获取优惠券
function getCoupons($memberId, $coupon_info, $get_type = 1, $invite_member_id = 0)
{
    $now_time = time();
    $insert_data = array(
        'member_id' => $memberId,
        'coupon_id' => $coupon_info['id'],
        'name' => $coupon_info['name'],
        'value' => $coupon_info['value'],
        'min_amount' => $coupon_info['min_amount'],
        'claimed_time' => $now_time,
        'start_time' => $now_time,
        'create_time' => time(),
        'get_type' => $get_type,
        'invite_member_id' => $invite_member_id,
        'desc' => $coupon_info['desc']
    );
    if ($coupon_info['effect_type'] == 1) {
        $insert_data['end_time'] = $coupon_info['effect_end'];
    } else {
        $insert_data['end_time'] = $now_time + ($coupon_info['effect_day'] * 86400);
    }
    //领取张数
    Db::name('coupons')
        ->where('id', '=', $coupon_info['id'])
        ->setInc('claimed_count');
    //增加会员优惠券
    $result_id = Db::name('member_coupons')->insertGetId($insert_data);
    return $result_id;
}
function getServer($memberId,$server_info){
    $now_time = time();
    $insert_data=array(
        'member_id'=>$memberId,
        'server_id'=>$server_info['id'],
        'num'=>1,
        'create_time'=>$now_time
    );
    $result_id = Db::name('member_server')->insertGetId($insert_data);
    return $result_id;
}

//接送服务回调接口
function driverPaySuccess($order_data,$pay_type=1)
{
    $order_update = array(
        'id' => $order_data['id'],
        'status' => 2,
        'pay_time' => time(),
        'pay_status' => 1,
        'pay_type' => 4,
        'fx_money'=>getFxMoney($order_data,2)
    );
//    dump($order_update);
//    die;
    Db::startTrans();
    try {
        Db::name('driver_order')->update($order_update);
        if ($order_data['mc_id']) {
            $mc_update = array(
                'id' => $order_data['mc_id'],
                'status' => 3,
            );
            Db::name('member_coupons')->update($mc_update);
        }
        Db::commit();
        return 1;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }
}
function serverPaySuccess($order_data,$pay_type=1){
    $order_update = array(
        'id' => $order_data['id'],
        'status' => 2,
        'pay_time' => time(),
        'pay_status' => 1,
        'pay_type'=>$pay_type
    );
    Db::startTrans();
    try {
        //关联的运输订单完成
        if ($order_data['is_car']==1){
            $driver_order=Db::name('driver_order')->where([
                'server_order_id'=>$order_data['id']
            ])->find();
            if ($driver_order){
                driverPaySuccess($driver_order);
            }
        }
        $order_update['fx_money']=getFxMoney($order_data,1);
        Db::name('server_order')->update($order_update);
        if ($order_data['mc_id']) {
            $mc_update = array(
                'id' => $order_data['mc_id'],
                'status' => 3,
            );
            Db::name('member_coupons')->update($mc_update);
        }
        Db::commit();
        return 1;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }
}
//type 1陪诊导诊 2司机订单 3套餐订单 4会员卡订单
function getFxMoney($order_info,$type=1){
    $member_info=Db::name('member')->find($order_info['member_id']);
    if ($order_info['pay_money']<=0){
        return 0;
    }
    $fx=Db::name('fx')->where([
        'member_id'=>$member_info['invite_id'],
        'status'=>1
    ])->find();

    $money =0;
    if ($fx){
        switch ($type) {
            case 1:
                $money= number_format($order_info['pay_money']*($fx['rate']/100),2);
                break;
            case 2:
                // 当expression等于value2时执行的代码
                $money= number_format($order_info['pay_money']*($fx['rate2']/100),2);
                break;
            case 3:
                $money=number_format($order_info['pay_money']*($fx['rate3']/100),2);
                break;
            case 4:
                $money= number_format($order_info['pay_money']*($fx['rate4']/100),2);
                break;
        }
    }
    return $money;
}
//陪诊 导诊订单退款
function tuikuanServerOrder($order_info,$tui_moeny=0.00, $is_houtui = 0)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'is_tui' => 1,
        'pay_status' => 2,
        'tui_time' => time(),
        'is_houtui' => $is_houtui,
        'tui_moeny'=>$tui_moeny
    );
    //优惠券
    if ($order_info['mc_id']) {
        Db::name('member_coupons')->update([
            'id' => $order_info['mc_id'],
            'status' => 1,
        ]);
    }
    //订单信息
    Db::name('server_order')->update($update_data);
}

function tuikuanDriverOrder($order_info,$tui_moeny=0.00, $is_houtui = 0)
{
    $update_data = array(
        'id' => $order_info['id'],
        'status' => 6,
        'is_tui' => 1,
        'pay_status' => 2,
        'tui_time' => time(),
        'is_houtui' => $is_houtui,
        'tui_moeny'=>$tui_moeny
    );
    //优惠券
    if ($order_info['mc_id']) {
        Db::name('member_coupons')->update([
            'id' => $order_info['mc_id'],
            'status' => 1,
        ]);
    }
    //订单信息
    Db::name('driver_order')->update($update_data);
}
//陪诊员 司机 分销 完成订单后加钱
//type 1陪诊 导诊服务 2司机服务 3分销订单收入 4陪诊提现 5司机提现 6分销提现
function addMoney($order_info,$type,$member_id,$money,$desc,$is_count=1,$fx_type=0,$junior_member_id=0){
    $insert_data=array(
        'member_id'=>$member_id,
        'is_count'=>$is_count,
        'money'=>$money,
        'type'=>$type,
        'order_id'=>$order_info['id'],
        'order_no'=>$order_info['order_no'],
        'desc'=>$desc,
        'fx_type'=>$fx_type,
        'junior_member_id'=>$junior_member_id,
        'create_time'=>time()
    );
    $insert_id=Db::name('member_finance')->insertGetId($insert_data);
    switch ($type) {
        case 1:
            // 当expression等于value1时执行的代码
            Db::name('pz')->where(['member_id'=>$member_id])->setInc('money',$money);
            break;
        case 2:
            // 当expression等于value2时执行的代码
            Db::name('driver')->where(['member_id'=>$member_id])->setInc('money',$money);
            break;
        case 3:
            Db::name('fx')->where(['member_id'=>$member_id])->setInc('money',$money);
            break;
        case 4:
            Db::name('pz')->where(['member_id'=>$member_id])->setDec('money',$money);
            break;
        case 5:
            Db::name('driver')->where(['member_id'=>$member_id])->setDec('money',$money);
            break;
        case 6:
            Db::name('fx')->where(['member_id'=>$member_id])->setDec('money',$money);
            break;
    }
}

function replaceAtCursor(&$string, $replacement, $cursor) {
    // 获取游标位置之前的部分
    $beforeCursor = substr($string, 0, $cursor);
    // 获取游标位置之后的部分
    $afterCursor = substr($string, $cursor);

    // 在游标位置插入替换字符串
    $string = $beforeCursor . $replacement . $afterCursor;
}

//激活会员
 function vip($mcard_id,$member_id)
{
    $insert_data = array(
        'mcard_id' => $mcard_id,
        'no' =>generateRandomNumbers(8),
        'secret' => generateRandomNumbers(16,true),
        'create_time' => time()
    );
    $mcard_list_id = Db::name('mcard_list')->insertGetId($insert_data);
    //完成激活
    activeCard($mcard_list_id, $member_id);
    return $mcard_list_id;
}
function addFxMoney($order_info, $type = 1,$member_info)
{
    //判断你的邀请用户是不是分销人员 invite_id
    $fx_info = Db::name('fx')
        ->where(['member_id' => $member_info['invite_id'], 'status' => 1, 'is_del' => 0])
        ->find();
    if (!$fx_info) {
        return 0;
    }
    $money = 0;
    $desc = '';
    //返现用户实际支付的钱
    switch ($type) {
        case 1:
            // 当expression等于value1时执行的代码
            $money = number_format($order_info['pay_money'] * ($fx_info['rate'] / 100), 2);
            $desc = '陪诊订单' . $order_info['order_no'];
            break;
        case 2:
            // 当expression等于value2时执行的代码
            $money = number_format($order_info['pay_money'] * ($fx_info['rate2'] / 100), 2);
            $desc = '接送订单' . $order_info['order_no'];
            break;
        case 3:
            $money = number_format($order_info['pay_money'] * ($fx_info['rate3'] / 100), 2);
            $desc = '购买套餐' . $order_info['order_no'];
            break;
        case 4:
            $money = number_format($order_info['pay_money'] * ($fx_info['rate4'] / 100), 2);
            $desc = '购买会员卡' . $order_info['order_no'];
            break;
    }
    if ($money) {
        addMoney($order_info, 3, $member_info['invite_id'], $money, $desc, 1, $type, $member_info);
    }
}

function giveMemberPackage2($package_id,$member_id)
{
    $package_data = Db::name('package')
        ->where(['id' => $package_id, 'is_del' => 0])
        ->find();
    if (!$package_data) {
        return 0;
    }
    $package_server = Db::name('package_server')->where(['package_id' => $package_id])->select();
    $create_time=time();
    $member_package_data = array(
        'member_id' => $member_id,
        'package_name' => $package_data['name'],
        'package_id' => $package_id,
        'create_time' => $create_time,
        //陪诊卡设置一年有效期
        'end_time' => $create_time + (365 * 86400),
//        'end_time' => time() + ($package_data['day_num'] * 86400)
    );
    $mp_id = Db::name('member_package')->insertGetId($member_package_data);
    $member_package_server_data = array();
    foreach ($package_server as $k => $v) {
        if ($v['num']){
            $time = $create_time;
            $member_package_server_data[] = [
                'mp_id' => $mp_id,
                'server_id' => $v['server_id'],
                'member_id' => $member_id,
                'server_num' => $v['num'],
                'num' => $v['num'],
                'create_time' => $time
            ];
        }
    }
    Db::name('member_package_server')->insertAll($member_package_server_data);
    return $mp_id;
}

function getPrice($server_id,$city){
    $order_detail = Db::name('server')->find($server_id);
    $price_info=Db::name('server_price')->where([
        ['is_del','=',0],
        ['province|city','=',$city],
        ['server_id','=',$server_id]
    ])->find();
    if ($price_info){
        return $price_info['price'];
    }
    return $order_detail['price'];
}

function tuikuanPackOrder($order_info, $order_id, $tui_type = 1)
{
    $update_date = array(
        'id' => $order_id,
//        'tui_type' => 1,
        'tui_time' => time(),
        'status' => 3
    );
    Db::name('package_order')->update($update_date);
    Db::name('member_package')->update([
        'id' => $order_info['mp_id'],
        'is_del' => 1
    ]);
    Db::name('member_package_server')
        ->where(['mp_id'=>$order_info['mp_id']])
        ->update([
            'is_del' => 1
        ]);
}
function tuikuanMcardOrder($order_info, $order_id, $tui_type = 1)
{
    $update_date = array(
        'id' => $order_id,
        'tui_time' => time(),
        'status' => 3
    );
    Db::name('mcard_order')->update($update_date);
    Db::name('mcard_list')->update([
        'id' => $order_info['mcard_list_id'],
        'is_del' => 1
    ]);
    Db::name('member_mcard_server')->where('id','=',$order_info['mcard_list_id'])->delete();
}

















